package com.e3.basdoc.warehouse.server;

import java.util.ArrayList;
import java.util.List;

import com.e3.basdoc.warehouse.client.WarehouseRPCService;
import com.e3.basdoc.warehouse.model.WarehouseModel;
import com.e3.basdoc.warehouse.model.WarehouseQC;
import com.e3.basdoc.warehouse.service.WarehouseQueryService;
import com.e3.basdoc.warehouse.service.WarehouseService;
import com.e3.core.base.ServiceException;
import com.e3.core.base.ServiceLocator;
import com.e3.web.core.client.WebException;
import com.e3.web.core.server.GwtRPCAction;
import com.e3.web.core.server.GwtRPCExecutor;
import com.e3.web.core.server.GwtRPCVoidExecutor;

public class WarehouseRPCServiceImpl extends GwtRPCAction implements
		WarehouseRPCService {

	private WarehouseService warehouseService;
	
	private WarehouseQueryService warehouseQueryService;
	
	private WarehouseService getWarehouseService(){
		if(warehouseService == null){
			warehouseService = ServiceLocator.getService(WarehouseService.class);
		}
		return warehouseService;
	}
	
	private WarehouseQueryService getWarehouseQueryService(){
		if(warehouseQueryService == null){
			warehouseQueryService = ServiceLocator.getQueryService(WarehouseQueryService.class);
		}
		return warehouseQueryService;
	}
	
	public WarehouseModel newWarehouse(final WarehouseModel model) throws WebException {
		return new GwtRPCExecutor<WarehouseModel>() {
			@Override
			public WarehouseModel execute() throws ServiceException, Exception {
				return getWarehouseService().newWarehouse(model);
			}
		}.doExecute();
	}

	public WarehouseModel modifyWarehouse(final WarehouseModel model) throws WebException {
		return new GwtRPCExecutor<WarehouseModel>() {
			@Override
			public WarehouseModel execute() throws ServiceException, Exception {
				return getWarehouseService().modifyWarehouse(model);
			}
		}.doExecute();
	}

	public List<WarehouseModel> getWarehouseByCondition(final WarehouseQC warehouseQC) throws WebException {
		return new GwtRPCExecutor<List<WarehouseModel>>() {
			@Override
			public List<WarehouseModel> execute() throws ServiceException, Exception {
				return getWarehouseQueryService().getWarehouseByCondition(warehouseQC);
			}
		}.doExecute();
	}

	public void deleteWarehouses(List<WarehouseModel> models) throws WebException {
		if(models == null||models.isEmpty()){
			return;
		}
		final List<Long> ids = new ArrayList<Long>(models.size());
		for (WarehouseModel warehouseModel : models) {
			ids.add(warehouseModel.getId());
		}
		
		new GwtRPCVoidExecutor() {
			@Override
			public void execute() throws ServiceException, Exception {
				getWarehouseService().deleteWarehouseByIds(ids);
			}
		}.doExecute();
	}

}
